package com.itheima.aop;

import com.itheima.Mapper.EmpLogMapper;

import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class EmpLoginAspect {

    @Autowired
    private EmpLogMapper empLogMapper;
    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Result result = (Result) pjp.proceed();
        long end = System.currentTimeMillis();
        EmpLoginLog empLoginLog = new EmpLoginLog();
        //1接收参数用户名密码
        Emp emp=(Emp) pjp.getArgs()[0];



        empLoginLog.setUsername(emp.getUsername());


        /*        empLoginLog.setUsername(pjp.getArgs()[0].toString().split(",")[1].split("=")[1]);
        log.info("{}",pjp.getArgs());*/
        //Emp(id=null, username=songjiang, password=123456, name=null, gender=null, phone=null, job=null, salary=null, image=null, entryDate=null, deptId=null, createTime=null, updateTime=null, deptName=null, exprList=null)

        /*        empLoginLog.setPassword(pjp.getArgs()[0].toString().split(",")[2].split("=")[1]);*/

        empLoginLog.setPassword(emp.getPassword());
        //2操作时间
        empLoginLog.setLoginTime(LocalDateTime.now());
        //3返回值，是否成功
        empLoginLog.setIsSuccess(result.getCode().shortValue());
        //4返回值jwt
        if(result.getData()!=null){
            //LoginInfo(id=2, username=songjiang, name=宋江, token=eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwiZXhwIjoxNzUxNTAyNjkyLCJ1c2VybmFtZSI6InNvbmdqaWFuZyJ9.nwo11eDrIOGcv_JiREnY2MgJO0_g2Oefj-zdjHS6wV0)
            empLoginLog.setJwt(result.getData().toString().split("=")[4].split("\\)")[0]);
        }else{
            empLoginLog.setJwt(null);
        }
        //5登录操作耗时
        empLoginLog.setCostTime(end-start);
        empLogMapper.loginLog(empLoginLog);
        return result;
    }
}